import pandas as pd  
from selenium import webdriver  
from selenium.webdriver.common.by import By  
from selenium.webdriver.chrome.service import Service  
from selenium.webdriver.chrome.options import Options  
from selenium.webdriver.support.ui import WebDriverWait  
from selenium.webdriver.support import expected_conditions as EC  
from selenium.common.exceptions import NoSuchElementException, TimeoutException  
from webdriver_manager.chrome import ChromeDriverManager  

import sys  
sys.stdout.reconfigure(encoding='utf-8')  # 解决输出乱码问题  

# 设置Chrome选项   
chrome_options = Options()  

driver = None  # 在try块外初始化driver变量  

# 用于存储爬取的数据  
data = []  

try:  
    # 使用webdriver-manager来自动管理ChromeDriver  
    service = Service(ChromeDriverManager().install())  
    driver = webdriver.Chrome(service=service, options=chrome_options)  
    
    # 打开目标网页  
    url = 'https://fundf10.eastmoney.com/jjjz_013128.html'  
    driver.get(url)  
    
    # 动态等待页面加载完成  
    try:  
        table = WebDriverWait(driver, 10).until(  
            EC.presence_of_element_located((By.CLASS_NAME, 'w782.comm.lsjz'))  
        )  
    except TimeoutException:  
        print("未能找到页面上的目标表格。")  
        exit()  

    # 提取表格数据  
    rows = table.find_elements(By.TAG_NAME, 'tr')  
    for row in rows[1:]:  # 跳过表头  
        columns = row.find_elements(By.TAG_NAME, 'td')  
        if len(columns) > 1:  # 确保行内有数据  
            date = columns[0].text.strip()  # 日期  
            net_value = columns[1].text.strip()  # 单位净值  
            accumulated_net_value = columns[2].text.strip()  # 累计净值  
            
            print(f"日期: {date}, 单位净值: {net_value}, 累计净值: {accumulated_net_value}")  
            
            # 将数据添加到列表中  
            data.append({"日期": date, "单位净值": net_value, "累计净值": accumulated_net_value})  

except NoSuchElementException as e:  
    print(f"元素未找到: {e}")  
except Exception as e:  
    print(f"发生错误: {e}")  
finally:  
    if driver:  
        driver.quit()  # 确保仅在driver被定义时才尝试关闭WebDriver  

# 使用pandas将数据保存到Excel文件  
df = pd.DataFrame(data)  
df.to_excel("基金净值数据.xlsx", index=False, engine='openpyxl')  

print("数据已成功保存到基金净值数据.xlsx")